<!--
 * @ Author: hongjiazhun
 * @ Create Time: 2023-03-10 20:01:09
 * @ Modified by: hongjiazhun
 * @ Modified time: 2023-04-02 13:25:02
 * @ Description:
 -->

<template>
  <div class="app-container">
    <avue-crud
      :search.sync="searchParams"
      v-model="form"
      @on-load="onLoad"
      :page.sync="page"
      ref="crud"
      :data="tableData"
      :option="option"
      :table-loading="loading"
      @selection-change="selectionChange"
      @row-save="rowSave"
      @row-update="rowUpdate"
      @refresh-change="refreshChange"
      @size-change="sizeChange"
      @current-change="currentChange"
      @search-change="searchChange"
      @search-reset="resetChange"
      :before-open="beforeOpen"
    >
      <template slot-scope="scope" slot="menuLeft">
        <el-button
          circle
          icon="el-icon-plus"
          @click="$refs.crud.rowAdd()"
          size="small"
        ></el-button>
        <el-button
          circle
          icon="el-icon-delete"
          size="small"
          @click="delHandle"
        ></el-button>
      </template>

      <template slot-scope="{ row, type }" slot="menu">
        <el-button
          :type="type"
          icon="el-icon-view"
          size="small"
          @click="checkDetails(row)"
          >详情</el-button
        >
      </template>
    </avue-crud>
  </div>
</template>

<script>
import { bsaeUrl, formatDate, getdiffdate } from "@/config/index";
import { getToken } from "@/utils/auth";
import {
  getList,
  addList,
  delList,
  updateList,
  getAllDays,
} from "@/api/arrangeClasses/index";

export default {
  name: "arrangeClasses",
  data() {
    return {
      tableData: [],
      page: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
      },
      loading: false,
      // 选择
      selectionData: [],
      form: {
        endDate: "",
        startDate: "",
      },
      // 搜索参数
      searchParams: {},
      isEdit: false,
      // 所有排班日期
      allDays: [],
    };
  },
  computed: {
    option() {
      return {
        // height: 200,
        border: true,
        columnBtn: false,
        delBtn: false,
        addBtn: false,
        selection: true,
        tip: false,
        // dialogDrag: true,
        searchMenuSpan: 4,
        column: [
          {
            label: "年度",
            prop: "scheduleYear",
            type: "year",
            format: "yyyy",
            valueFormat: "yyyy",
            rules: [
              {
                required: true,
                message: "请选择年度",
                trigger: "blur",
              },
            ],
            disabled: this.isEdit,
          },
          {
            label: "排班类型",
            prop: "scheduleType",
            search: true,
            type: "select",
            searchSpan: 5,
            props: {
              label: "dictLabel",
              value: "dictValue",
            },
            dicUrl: `${bsaeUrl}/system/dict/data/list?dictType=xmu_schedule_type`,
            dicHeaders: {
              Authorization: "Bearer " + getToken(),
            },
            dicFormatter: (res) => {
              const { rows = [], code } = res;
              return code === 200 ? rows : [];
            },
            rules: [
              {
                required: true,
                message: "请选择排班类型",
                trigger: "blur",
              },
            ],
            disabled: this.isEdit,
          },
          // {
          //   label: "起止时间",
          //   prop: "date",
          //   type: "daterange",
          //   format: "yyyy-MM-dd",
          //   valueFormat: "yyyy-MM-dd",
          //   startPlaceholder: "开始时间",
          //   endPlaceholder: "结束时间",
          //   rangeSeparator: "至",
          //   pickerOptions: {
          //     disabledDate(time) {
          //       return time.getTime() < Date.now() - 3600 * 1000 * 24;
          //     },
          //   },
          //   rules: [
          //     {
          //       required: true,
          //       message: "请选择起止时间",
          //       trigger: "blur",
          //     },
          //   ],
          // },
          {
            label: "开始时间",
            prop: "startDate",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            rules: [
              {
                required: true,
                message: "请选择开始时间",
                trigger: "blur",
              },
            ],
            pickerOptions: {
              disabledDate: (time) => {
                let _time = "";
                if (this.allDays.length !== 0) {
                  _time = formatDate(time);
                }
                return (
                  time.getTime() < new Date().getTime() - 3600 * 1000 * 24 ||
                  this.allDays.includes(_time)
                );
              },
            },
            // 结束时间
            change: ({ value }) => {
              const { endDate = "" } = this.form;
              if (value && endDate) {
                const startTime = new Date(value).getTime();
                const endTime = new Date(endDate).getTime();
                if (startTime > endTime) {
                  this.$message.error("开始时间不能晚于结束时间!");
                  setTimeout(() => {
                    this.form = {
                      ...this.form,
                      startDate: endDate,
                    };
                    this.checkStartAndEndDate();
                  }, 200);
                } else {
                  !this.isEdit &&
                    setTimeout(() => {
                      this.checkStartAndEndDate();
                    }, 200);
                }
              }
            },
          },
          {
            label: "结束时间",
            prop: "endDate",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            rules: [
              {
                required: true,
                message: "请选择结束时间",
                trigger: "blur",
              },
            ],
            pickerOptions: {
              disabledDate: (time) => {
                let _time = "";
                if (this.allDays.length !== 0) {
                  _time = formatDate(time);
                }
                return (
                  time.getTime() < new Date().getTime() - 3600 * 1000 * 24 ||
                  this.allDays.includes(_time)
                );
              },
            },
            // 结束时间
            change: ({ value }) => {
              const { startDate = "" } = this.form;
              if (value && startDate) {
                const startTime = new Date(startDate).getTime();
                const endTime = new Date(value).getTime();
                if (startTime > endTime) {
                  this.$message.error("结束时间不能早于开始时间!");
                  setTimeout(() => {
                    this.form = {
                      ...this.form,
                      endDate: startDate,
                    };
                  }, 200);
                } else {
                  !this.isEdit &&
                    setTimeout(() => {
                      this.checkStartAndEndDate();
                    }, 200);
                }
              }
            },
          },
        ],
      };
    },
  },
  methods: {
    // 获取数据
    async onLoad() {
      this.loading = true;
      const { currentPage = 1, pageSize } = this.page;
      // 设置请求参数
      const params = {
        pageNum: currentPage,
        pageSize,
        ...this.searchParams,
      };
      const { code, rows = [], total, msg } = await getList(params);
      this.tableData = code === 200 ? rows : [];
      this.loading = false;
      // 设置总条数
      this.page.total = total;
      code === 200 && this.getScheduleAllDays();
    },
    // 刷新
    refreshChange() {
      this.onLoad();
    },
    // 条数
    sizeChange(val) {
      this.page.currentPage = 1;
      this.page.pageSize = val;
    },
    // 页数
    currentChange(val) {
      this.page.currentPage = val;
    },
    resetChange(item) {
      this.onLoad();
    },
    searchChange(params, done) {
      this.onLoad();
      done();
    },
    // 多选
    selectionChange(selection) {
      this.selectionData = selection;
    },
    // 新增数据
    async rowSave(form, done, loading) {
      const { code, msg } = await addList(form);
      this.$message({
        type: code === 200 ? "success" : "error",
        message: msg,
      });
      this.onLoad();
      loading();
      done();
    },
    // 编辑
    async rowUpdate(form, index, done, loading) {
      const { code, msg } = await updateList(form);
      this.$message({
        type: code === 200 ? "success" : "error",
        message: msg,
      });
      loading();
      done(form);
      this.getScheduleAllDays();
    },
    // 删除数据
    delHandle() {
      if (this.selectionData.length === 0) {
        this.$message.error("请选择需要删除的数据！");
        return;
      }
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.delSecondConfirm();
          // // 获取ids
          // const scheduleTableIds = this.selectionData
          //   .map((v) => v.scheduleTableId)
          //   .join(",");
          // // 获取回调
          // const { code, msg } = await delList(scheduleTableIds);
          // this.$message({
          //   type: code === 200 ? "success" : "error",
          //   message: msg,
          // });
          // // 清空多选数据
          // this.selectionData = [];
          // // 重新请求
          // this.onLoad();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    delSecondConfirm() {
      this.$confirm("请再次确认是否删除该数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 获取ids
          const scheduleTableIds = this.selectionData
            .map((v) => v.scheduleTableId)
            .join(",");
          // 获取回调
          const { code, msg } = await delList(scheduleTableIds);
          this.$message({
            type: code === 200 ? "success" : "error",
            message: msg,
          });
          // 清空多选数据
          this.selectionData = [];
          // 重新请求
          this.onLoad();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 查看详情
    checkDetails(row = {}) {
      const { scheduleTableId = "" } = row;
      this.$router.push(
        `/arrangeClasses/count?scheduleTableId=${scheduleTableId}`
      );
      // this.$router.push("/arrangeClasses/details");
    },
    beforeOpen(done, type) {
      this.isEdit = type === "edit" ? true : false;
      done();
    },
    // 获取所有排班
    async getScheduleAllDays() {
      const { code, data = [] } = await getAllDays();
      this.allDays = code === 200 ? data : [];
    },
    // 检验选择开始和结束时间，是否包含已排班的日期
    checkStartAndEndDate() {
      const { startDate, endDate } = this.form;
      // 校验时间
      if (startDate !== endDate) {
        // 获取两个日期之间的时间
        let result = getdiffdate(startDate, endDate);
        const result2 = result.filter((r) => this.allDays.includes(r)) || [];
        // 判断是否存在排班
        if (result2.length !== 0) {
          this.$message.error("已选日期之间有存在排班，请重新选择!");
          this.form = {
            ...this.form,
            startDate: "",
            endDate: "",
          };
        }
      }
    },
  },
  mounted() {
    this.getScheduleAllDays();
  },
};
</script>

<style lang="scss" scoped>
</style>